<template>
  <div class="vulnerability-trends-container">
    <el-card class="trends-card">
      <template #header>
        <div class="card-header">
          <h2>漏洞趋势分析</h2>
          <div class="header-actions">
            <el-button type="primary" @click="refreshTrends">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button @click="exportTrendsData">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 分析配置区 -->
      <div class="analysis-config">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-value="[defaultStartDate, defaultEndDate]"
              :picker-options="datePickerOptions"
              @change="handleDateRangeChange"
            />
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="timeInterval"
              placeholder="选择时间间隔"
              @change="updateCharts"
            >
              <el-option label="日" value="day" />
              <el-option label="周" value="week" />
              <el-option label="月" value="month" />
              <el-option label="季度" value="quarter" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="chartType"
              placeholder="图表类型"
              @change="updateCharts"
            >
              <el-option label="折线图" value="line" />
              <el-option label="柱状图" value="bar" />
              <el-option label="面积图" value="area" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="assetGroup"
              placeholder="资产分组"
              clearable
              @change="updateCharts"
            >
              <el-option label="全部资产" value="all" />
              <el-option label="Web应用" value="web_apps" />
              <el-option label="API服务" value="api_services" />
              <el-option label="服务器" value="servers" />
              <el-option label="数据库" value="databases" />
              <el-option label="网络设备" value="network_devices" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="selectedVulnerabilityTypes"
              multiple
              filterable
              placeholder="漏洞类型"
              @change="updateCharts"
            >
              <el-option label="SQL注入" value="sql_injection" />
              <el-option label="跨站脚本(XSS)" value="xss" />
              <el-option label="命令注入" value="command_injection" />
              <el-option label="跨站请求伪造(CSRF)" value="csrf" />
              <el-option label="信息泄露" value="information_disclosure" />
              <el-option label="未授权访问" value="unauthorized_access" />
              <el-option label="配置错误" value="configuration_error" />
              <el-option label="缓冲区溢出" value="buffer_overflow" />
              <el-option label="密码策略" value="password_policy" />
              <el-option label="过时组件" value="outdated_components" />
            </el-select>
          </el-col>
        </el-row>
        
        <!-- 高级筛选 -->
        <el-collapse class="advanced-filters">
          <el-collapse-item title="高级筛选">
            <el-row :gutter="20" style="margin-top: 10px;">
              <el-col :span="6">
                <el-select
                  v-model="scanTypes"
                  multiple
                  placeholder="扫描类型"
                  @change="updateCharts"
                >
                  <el-option label="主动扫描" value="active" />
                  <el-option label="被动扫描" value="passive" />
                  <el-option label="漏洞验证" value="verification" />
                  <el-option label="合规扫描" value="compliance" />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-select
                  v-model="scanTools"
                  multiple
                  placeholder="扫描工具"
                  @change="updateCharts"
                >
                  <el-option label="内部扫描器" value="internal_scanner" />
                  <el-option label="Nessus" value="nessus" />
                  <el-option label="OpenVAS" value="openvas" />
                  <el-option label="OWASP ZAP" value="zap" />
                  <el-option label="Burp Suite" value="burp" />
                  <el-option label="Nuclei" value="nuclei" />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-checkbox-group v-model="severityFilters" @change="updateCharts">
                  <el-checkbox :label="'critical'">严重</el-checkbox>
                  <el-checkbox :label="'high'">高危</el-checkbox>
                  <el-checkbox :label="'medium'">中危</el-checkbox>
                  <el-checkbox :label="'low'">低危</el-checkbox>
                </el-checkbox-group>
              </el-col>
              <el-col :span="6">
                <el-checkbox-group v-model="statusFilters" @change="updateCharts">
                  <el-checkbox :label="'new'">新发现</el-checkbox>
                  <el-checkbox :label="'fixed'">已修复</el-checkbox>
                  <el-checkbox :label="'recurring'">重复发现</el-checkbox>
                </el-checkbox-group>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </div>

      <!-- 关键指标概览 -->
      <div class="metrics-overview">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="metric-header">
                  <span>总漏洞数</span>
                  <el-icon><Warning /></el-icon>
                </div>
              </template>
              <div class="metric-content">
                <el-statistic :value="totalVulnerabilities" :precision="0">
                  <template #suffix>
                    <el-tooltip content="相比上期">
                      <span class="trend-indicator" :class="totalVulnerabilitiesTrendClass">
                        <el-icon v-if="totalVulnerabilitiesTrend > 0"><ArrowUp /></el-icon>
                        <el-icon v-else-if="totalVulnerabilitiesTrend < 0"><ArrowDown /></el-icon>
                        <el-icon v-else><Minus /></el-icon>
                        {{ Math.abs(totalVulnerabilitiesTrend) }}%
                      </span>
                    </el-tooltip>
                  </template>
                </el-statistic>
                <div class="metric-details">
                  <span>新增: {{ newVulnerabilities }}</span>
                  <span>修复: {{ fixedVulnerabilities }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="metric-header">
                  <span>平均修复时间</span>
                  <el-icon><Clock /></el-icon>
                </div>
              </template>
              <div class="metric-content">
                <el-statistic :value="averageFixTime" :precision="1">
                  <template #suffix>
                    天
                  </template>
                </el-statistic>
                <div class="metric-details">
                  <span>严重: {{ criticalFixTime }} 天</span>
                  <span>高危: {{ highFixTime }} 天</span>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="metric-header">
                  <span>风险评分</span>
                  <el-icon><StarFilled /></el-icon>
                </div>
              </template>
              <div class="metric-content">
                <el-statistic :value="riskScore" :precision="1">
                  <template #suffix>
                    / 100
                  </template>
                </el-statistic>
                <div class="risk-level" :class="getRiskLevelClass(riskScore)">
                  {{ getRiskLevelText(riskScore) }}
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="metric-header">
                  <span>修复率</span>
                  <el-icon><Check /></el-icon>
                </div>
              </template>
              <div class="metric-content">
                <el-statistic :value="fixRate" :precision="1">
                  <template #suffix>
                    %
                  </template>
                </el-statistic>
                <div class="metric-details">
                  <span>合规率: {{ complianceRate }}%</span>
                  <span>覆盖率: {{ coverageRate }}%</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 主要趋势图表 -->
      <div class="trends-charts">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>漏洞数量趋势</span>
              <div class="chart-controls">
                <el-radio-group v-model="vulnerabilityTrendType" size="small" @change="updateCharts">
                  <el-radio-button label="total">累计</el-radio-button>
                  <el-radio-button label="new">新增</el-radio-button>
                  <el-radio-button label="fixed">修复</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container" ref="vulnerabilityTrendChart"></div>
        </el-card>

        <!-- 严重程度分布趋势 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>严重程度分布趋势</span>
              <el-dropdown @command="handleSeverityChartCommand">
                <span class="el-dropdown-link">
                  操作 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="stack">堆叠显示</el-dropdown-item>
                    <el-dropdown-item command="group">分组显示</el-dropdown-item>
                    <el-dropdown-item command="normal">普通显示</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          <div class="chart-container" ref="severityTrendChart"></div>
        </el-card>

        <!-- 漏洞类型分布 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>漏洞类型分布</span>
                </div>
              </template>
              <div class="chart-container" ref="vulnerabilityTypeChart"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>资产类型漏洞分布</span>
                </div>
              </template>
              <div class="chart-container" ref="assetTypeChart"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 修复时间分析 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>平均修复时间趋势</span>
              <div class="chart-controls">
                <el-radio-group v-model="fixTimeTrendType" size="small" @change="updateCharts">
                  <el-radio-button label="by_severity">按严重程度</el-radio-button>
                  <el-radio-button label="by_type">按漏洞类型</el-radio-button>
                  <el-radio-button label="by_asset">按资产类型</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container" ref="fixTimeTrendChart"></div>
        </el-card>

        <!-- 趋势预测 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>趋势预测</span>
              <div class="chart-controls">
                <el-select v-model="predictionDays" size="small" @change="updatePredictionChart">
                  <el-option label="7天" :value="7" />
                  <el-option label="30天" :value="30" />
                  <el-option label="90天" :value="90" />
                </el-select>
              </div>
            </div>
          </template>
          <div class="chart-container" ref="predictionChart"></div>
        </el-card>

        <!-- 异常检测 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>异常检测</span>
              <el-tag v-if="anomalies.length > 0" type="danger" effect="dark">{{ anomalies.length }} 个异常</el-tag>
            </div>
          </template>
          <div class="chart-container" ref="anomalyChart"></div>
          <div class="anomalies-list" v-if="anomalies.length > 0">
            <h4>检测到的异常事件</h4>
            <el-table :data="anomalies" style="width: 100%" size="small">
              <el-table-column prop="date" label="日期" width="120" />
              <el-table-column prop="type" label="异常类型" width="150">
                <template #default="scope">
                  <el-tag :type="getAnomalyTypeTag(scope.row.type)">{{ scope.row.type }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="severity" label="严重程度" width="100">
                <template #default="scope">
                  <el-tag :type="getSeverityTag(scope.row.severity)">{{ scope.row.severity }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" fixed="right">
                <template #default="scope">
                  <el-button type="primary" link size="small" @click="viewAnomalyDetails(scope.row)">
                    查看
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>

      <!-- 分析总结 -->
      <div class="analysis-summary">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>趋势分析总结</h3>
            </div>
          </template>
          <div class="summary-content">
            <div class="summary-section">
              <h4>总体趋势</h4>
              <p>{{ summary.overallTrend }}</p>
            </div>
            <div class="summary-section">
              <h4>关键发现</h4>
              <ul>
                <li v-for="(finding, index) in summary.keyFindings" :key="index">{{ finding }}</li>
              </ul>
            </div>
            <div class="summary-section">
              <h4>风险提示</h4>
              <ul>
                <li v-for="(warning, index) in summary.warnings" :key="index">{{ warning }}</li>
              </ul>
            </div>
            <div class="summary-section">
              <h4>建议措施</h4>
              <ul>
                <li v-for="(recommendation, index) in summary.recommendations" :key="index">{{ recommendation }}</li>
              </ul>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 异常详情对话框 -->
    <el-dialog
      v-model="showAnomalyDetailsDialog"
      title="异常事件详情"
      width="600px"
    >
      <div class="anomaly-details" v-if="selectedAnomaly">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="异常ID">{{ selectedAnomaly.id }}</el-descriptions-item>
          <el-descriptions-item label="检测时间">{{ selectedAnomaly.date }}</el-descriptions-item>
          <el-descriptions-item label="异常类型">
            <el-tag :type="getAnomalyTypeTag(selectedAnomaly.type)">{{ selectedAnomaly.type }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="严重程度">
            <el-tag :type="getSeverityTag(selectedAnomaly.severity)">{{ selectedAnomaly.severity }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述">{{ selectedAnomaly.description }}</el-descriptions-item>
          <el-descriptions-item label="详细信息">{{ selectedAnomaly.details }}</el-descriptions-item>
          <el-descriptions-item label="影响范围">{{ selectedAnomaly.affectedScope }}</el-descriptions-item>
          <el-descriptions-item label="建议措施">{{ selectedAnomaly.recommendations }}</el-descriptions-item>
          <el-descriptions-item label="置信度">{{ selectedAnomaly.confidence }}%</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAnomalyDetailsDialog = false">关闭</el-button>
          <el-button type="primary" @click="exportAnomalyDetails">导出详情</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 全局加载遮罩 -->
    <div v-if="loading" class="loading-mask">
      <el-loading :text="loadingText"></el-loading>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { Refresh, Download, Warning, Clock, StarFilled, Check, ArrowUp, ArrowDown, Minus, ArrowDown as DropdownArrow } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import apiService from '../services/apiService.js'
import { formatDate, formatDateTime } from '../utils/dateUtils.js'

// 响应式数据
const loading = ref(false)
const loadingText = ref('加载中...')
const dateRange = ref([])
const timeInterval = ref('week')
const chartType = ref('line')
const assetGroup = ref('all')
const selectedVulnerabilityTypes = ref([])
const scanTypes = ref([])
const scanTools = ref([])
const severityFilters = ref(['critical', 'high', 'medium', 'low'])
const statusFilters = ref(['new', 'fixed', 'recurring'])
const vulnerabilityTrendType = ref('total')
const fixTimeTrendType = ref('by_severity')
const predictionDays = ref(30)
const severityChartMode = ref('normal')
const showAnomalyDetailsDialog = ref(false)
const selectedAnomaly = ref(null)

// 图表实例引用
const vulnerabilityTrendChart = ref(null)
const severityTrendChart = ref(null)
const vulnerabilityTypeChart = ref(null)
const assetTypeChart = ref(null)
const fixTimeTrendChart = ref(null)
const predictionChart = ref(null)
const anomalyChart = ref(null)

// 图表实例
let chartInstances = {
  vulnerabilityTrend: null,
  severityTrend: null,
  vulnerabilityType: null,
  assetType: null,
  fixTimeTrend: null,
  prediction: null,
  anomaly: null
}

// 默认日期范围（过去90天）
const today = new Date()
const defaultEndDate = today
const defaultStartDate = new Date(today.getTime() - 90 * 24 * 60 * 60 * 1000)

const datePickerOptions = {
  disabledDate(time) {
    return time.getTime() > today.getTime()
  }
}

// 模拟数据 - 在实际项目中应该从API获取
const mockTrendData = ref({
  dates: [],
  totalVulnerabilities: [],
  newVulnerabilities: [],
  fixedVulnerabilities: [],
  critical: [],
  high: [],
  medium: [],
  low: [],
  vulnerabilityTypes: {},
  assetTypes: {},
  fixTimes: {},
  predictions: {
    dates: [],
    totalVulnerabilities: [],
    confidence: []
  },
  anomalies: []
})

// 计算属性
const totalVulnerabilities = computed(() => {
  if (mockTrendData.value.totalVulnerabilities.length === 0) return 0
  return mockTrendData.value.totalVulnerabilities[mockTrendData.value.totalVulnerabilities.length - 1]
})

const totalVulnerabilitiesTrend = computed(() => {
  const data = mockTrendData.value.totalVulnerabilities
  if (data.length < 2) return 0
  const current = data[data.length - 1]
  const previous = data[data.length - 2]
  return ((current - previous) / previous * 100).toFixed(1)
})

const totalVulnerabilitiesTrendClass = computed(() => {
  const trend = totalVulnerabilitiesTrend.value
  if (trend > 0) return 'trend-up'
  if (trend < 0) return 'trend-down'
  return 'trend-neutral'
})

const newVulnerabilities = computed(() => {
  if (mockTrendData.value.newVulnerabilities.length === 0) return 0
  return mockTrendData.value.newVulnerabilities.reduce((sum, val) => sum + val, 0)
})

const fixedVulnerabilities = computed(() => {
  if (mockTrendData.value.fixedVulnerabilities.length === 0) return 0
  return mockTrendData.value.fixedVulnerabilities.reduce((sum, val) => sum + val, 0)
})

const averageFixTime = computed(() => {
  // 模拟平均修复时间
  return 8.5
})

const criticalFixTime = computed(() => {
  // 模拟严重漏洞修复时间
  return 2.3
})

const highFixTime = computed(() => {
  // 模拟高危漏洞修复时间
  return 5.7
})

const riskScore = computed(() => {
  // 模拟风险评分
  return 67.2
})

const fixRate = computed(() => {
  // 模拟修复率
  return 72.5
})

const complianceRate = computed(() => {
  // 模拟合规率
  return 83.7
})

const coverageRate = computed(() => {
  // 模拟覆盖率
  return 91.2
})

const anomalies = computed(() => {
  return mockTrendData.value.anomalies
})

const summary = computed(() => {
  return {
    overallTrend: '过去90天内，漏洞数量呈现先上升后下降的趋势，最近30天修复率有所提升。整体安全状况正在改善，但仍需关注新发现的高危漏洞。',
    keyFindings: [
      'SQL注入漏洞数量较上期增加了15%，主要集中在API服务中',
      'Web应用的修复速度明显提升，平均修复时间从12天降至8天',
      '服务器配置错误类漏洞大幅减少，说明配置管理有所加强',
      '高危漏洞的重复发现率从25%降至15%，修复质量有所提高'
    ],
    warnings: [
      '近期API服务中发现了多个新型XSS漏洞，需要进一步加强输入验证',
      '数据库服务器的补丁更新滞后，存在多个已知漏洞',
      '部分Web应用的认证机制存在绕过风险，建议进行全面审查',
      '移动端应用的安全测试覆盖率较低，可能存在未发现的漏洞'
    ],
    recommendations: [
      '加强对API服务的安全测试和代码审查，重点关注SQL注入和XSS漏洞',
      '建立自动化补丁管理流程，确保服务器和应用及时更新',
      '对所有Web应用的认证和授权机制进行全面审计',
      '增加移动端应用的安全测试覆盖，引入专门的移动应用安全测试工具',
      '制定更严格的密码策略和多因素认证要求'
    ]
  }
})

// 方法
const loadTrendData = async () => {
  loading.value = true
  loadingText.value = '加载趋势数据...'
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    // const response = await apiService.getVulnerabilityTrends({
    //   startDate: formatDate(dateRange.value[0]),
    //   endDate: formatDate(dateRange.value[1]),
    //   timeInterval: timeInterval.value,
    //   assetGroup: assetGroup.value,
    //   vulnerabilityTypes: selectedVulnerabilityTypes.value,
    //   severityFilters: severityFilters.value
    // })
    
    // 生成模拟数据
    generateMockData()
  } catch (error) {
    console.error('加载趋势数据失败:', error)
    ElMessage.error('加载趋势数据失败，请重试')
  } finally {
    loading.value = false
  }
}

const generateMockData = () => {
  const start = dateRange.value.length > 0 ? dateRange.value[0] : defaultStartDate
  const end = dateRange.value.length > 0 ? dateRange.value[1] : defaultEndDate
  const dates = []
  const totalVulnerabilities = []
  const newVulnerabilities = []
  const fixedVulnerabilities = []
  const critical = []
  const high = []
  const medium = []
  const low = []
  
  // 根据时间间隔生成日期
  const current = new Date(start)
  let count = 0
  let total = 120 // 初始漏洞数量
  
  while (current <= end) {
    dates.push(formatDate(current))
    
    // 生成模拟数据
    const newCount = Math.floor(Math.random() * 10) + 2
    const fixedCount = Math.floor(Math.random() * 8) + 1
    total = Math.max(0, total + newCount - fixedCount)
    
    totalVulnerabilities.push(total)
    newVulnerabilities.push(newCount)
    fixedVulnerabilities.push(fixedCount)
    
    // 严重程度分布
    const criticalCount = Math.floor(total * 0.1)
    const highCount = Math.floor(total * 0.25)
    const mediumCount = Math.floor(total * 0.35)
    const lowCount = total - criticalCount - highCount - mediumCount
    
    critical.push(criticalCount)
    high.push(highCount)
    medium.push(mediumCount)
    low.push(lowCount)
    
    // 根据时间间隔增加日期
    switch (timeInterval.value) {
      case 'day':
        current.setDate(current.getDate() + 1)
        break
      case 'week':
        current.setDate(current.getDate() + 7)
        break
      case 'month':
        current.setMonth(current.getMonth() + 1)
        break
      case 'quarter':
        current.setMonth(current.getMonth() + 3)
        break
    }
    
    count++
  }
  
  // 漏洞类型分布
  const vulnerabilityTypes = {
    'sql_injection': Math.floor(total * 0.15),
    'xss': Math.floor(total * 0.18),
    'command_injection': Math.floor(total * 0.08),
    'csrf': Math.floor(total * 0.12),
    'information_disclosure': Math.floor(total * 0.16),
    'unauthorized_access': Math.floor(total * 0.14),
    'configuration_error': Math.floor(total * 0.09),
    'buffer_overflow': Math.floor(total * 0.03),
    'password_policy': Math.floor(total * 0.04),
    'outdated_components': Math.floor(total * 0.01)
  }
  
  // 资产类型分布
  const assetTypes = {
    'web_apps': Math.floor(total * 0.4),
    'api_services': Math.floor(total * 0.25),
    'servers': Math.floor(total * 0.2),
    'databases': Math.floor(total * 0.1),
    'network_devices': Math.floor(total * 0.05)
  }
  
  // 修复时间数据
  const fixTimes = {
    'by_severity': {
      'critical': 2.3,
      'high': 5.7,
      'medium': 14.2,
      'low': 28.5
    },
    'by_type': {
      'web_apps': 8.2,
      'api_services': 10.5,
      'servers': 15.3,
      'databases': 12.8,
      'network_devices': 20.1
    },
    'by_vulnerability': {
      'sql_injection': 7.5,
      'xss': 9.2,
      'command_injection': 6.8,
      'csrf': 11.5,
      'information_disclosure': 14.3
    }
  }
  
  // 生成预测数据
  const predictions = generatePredictions(dates, totalVulnerabilities, predictionDays.value)
  
  // 生成异常数据
  const anomalies = generateAnomalies(dates, newVulnerabilities)
  
  mockTrendData.value = {
    dates,
    totalVulnerabilities,
    newVulnerabilities,
    fixedVulnerabilities,
    critical,
    high,
    medium,
    low,
    vulnerabilityTypes,
    assetTypes,
    fixTimes,
    predictions,
    anomalies
  }
}

const generatePredictions = (dates, totalVulnerabilities, days) => {
  const lastDate = new Date(dates[dates.length - 1])
  const lastValue = totalVulnerabilities[totalVulnerabilities.length - 1]
  const predDates = []
  const predValues = []
  const confidence = []
  
  // 简单线性预测（实际项目中应该使用更复杂的预测算法）
  let trend = 0
  if (totalVulnerabilities.length > 1) {
    const firstValue = totalVulnerabilities[0]
    const lastValue = totalVulnerabilities[totalVulnerabilities.length - 1]
    trend = (lastValue - firstValue) / totalVulnerabilities.length
  }
  
  let currentValue = lastValue
  
  for (let i = 1; i <= days; i++) {
    const nextDate = new Date(lastDate)
    nextDate.setDate(nextDate.getDate() + i)
    predDates.push(formatDate(nextDate))
    
    // 添加一些随机波动
    const fluctuation = (Math.random() - 0.5) * 10
    currentValue = Math.max(0, currentValue + trend + fluctuation)
    predValues.push(Math.round(currentValue))
    
    // 随着预测时间增加，置信度降低
    const conf = Math.max(50, 95 - (i * 0.5))
    confidence.push(conf)
  }
  
  return { dates: predDates, totalVulnerabilities: predValues, confidence }
}

const generateAnomalies = (dates, newVulnerabilities) => {
  const anomalies = []
  
  // 检测异常（简化版，实际项目中应该使用更复杂的异常检测算法）
  const avgNewVulns = newVulnerabilities.reduce((sum, val) => sum + val, 0) / newVulnerabilities.length
  const stdDev = Math.sqrt(
    newVulnerabilities.reduce((sum, val) => sum + Math.pow(val - avgNewVulns, 2), 0) / newVulnerabilities.length
  )
  
  newVulnerabilities.forEach((count, index) => {
    // 如果超过平均值的2个标准差，视为异常
    if (count > avgNewVulns + 2 * stdDev) {
      anomalies.push({
        id: `ANOMALY-${index + 1}`,
        date: dates[index],
        type: '漏洞数量激增',
        severity: 'high',
        description: `检测到异常数量的新漏洞: ${count}个（正常平均值: ${avgNewVulns.toFixed(1)}个）`,
        details: `在${dates[index]}这一天，新发现的漏洞数量显著高于正常水平。建议检查当天是否有新的应用上线或大规模变更。`,
        affectedScope: 'Web应用和API服务',
        recommendations: '立即对新增漏洞进行优先级评估，对高危漏洞进行紧急修复，并审查当天的变更记录。',
        confidence: 85
      })
    }
  })
  
  // 添加一些模拟的其他类型异常
  anomalies.push({
    id: 'ANOMALY-TYPE-1',
    date: dates[Math.floor(dates.length * 0.3)],
    type: '高危漏洞集中',
    severity: 'critical',
    description: '在短时间内集中发现多个高危SQL注入漏洞',
    details: '在同一时间段内，多个应用模块同时发现类似的SQL注入漏洞，可能是系统性问题或共享组件存在缺陷。',
    affectedScope: '多个内部应用系统',
    recommendations: '立即检查共享数据库访问组件，对所有使用该组件的应用进行紧急审计和修复。',
    confidence: 92
  })
  
  anomalies.push({
    id: 'ANOMALY-TYPE-2',
    date: dates[Math.floor(dates.length * 0.7)],
    type: '修复率异常下降',
    severity: 'medium',
    description: '修复率较前一周期下降了40%',
    details: '修复率的显著下降可能表明修复资源不足或流程存在问题。',
    affectedScope: '整体安全管理流程',
    recommendations: '审查修复流程，评估资源分配情况，考虑临时增加修复资源或调整优先级策略。',
    confidence: 78
  })
  
  return anomalies
}

const initCharts = () => {
  // 初始化所有图表
  initVulnerabilityTrendChart()
  initSeverityTrendChart()
  initVulnerabilityTypeChart()
  initAssetTypeChart()
  initFixTimeTrendChart()
  initPredictionChart()
  initAnomalyChart()
}

const initVulnerabilityTrendChart = () => {
  if (vulnerabilityTrendChart.value) {
    chartInstances.vulnerabilityTrend = echarts.init(vulnerabilityTrendChart.value)
    updateVulnerabilityTrendChart()
  }
}

const updateVulnerabilityTrendChart = () => {
  if (!chartInstances.vulnerabilityTrend) return
  
  let data = []
  let seriesName = ''
  let color = ''
  
  switch (vulnerabilityTrendType.value) {
    case 'total':
      data = mockTrendData.value.totalVulnerabilities
      seriesName = '累计漏洞数'
      color = '#5470c6'
      break
    case 'new':
      data = mockTrendData.value.newVulnerabilities
      seriesName = '新增漏洞数'
      color = '#ee6666'
      break
    case 'fixed':
      data = mockTrendData.value.fixedVulnerabilities
      seriesName = '修复漏洞数'
      color = '#91cc75'
      break
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e0e6ed',
      textStyle: {
        color: '#303133'
      },
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: mockTrendData.value.dates,
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      axisLabel: {
        color: '#606266',
        rotate: timeInterval.value === 'day' ? 45 : 0
      }
    },
    yAxis: {
      type: 'value',
      name: '数量',
      nameTextStyle: {
        color: '#606266'
      },
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      axisLabel: {
        color: '#606266',
        formatter: '{value}'
      },
      splitLine: {
        lineStyle: {
          color: '#f0f2f5',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: seriesName,
        type: chartType.value,
        data: data,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: color
        },
        lineStyle: {
          width: 3
        },
        areaStyle: {
          opacity: 0.3
        },
        emphasis: {
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 2,
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.2)'
          }
        },
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ],
          symbolSize: 60
        },
        markLine: {
          data: [
            { type: 'average', name: '平均值' }
          ]
        }
      }
    ],
    animation: true
  }
  
  chartInstances.vulnerabilityTrend.setOption(option)
}

const initSeverityTrendChart = () => {
  if (severityTrendChart.value) {
    chartInstances.severityTrend = echarts.init(severityTrendChart.value)
    updateSeverityTrendChart()
  }
}

const updateSeverityTrendChart = () => {
  if (!chartInstances.severityTrend) return
  
  const series = [
    {
      name: '严重',
      type: chartType.value,
      data: mockTrendData.value.critical,
      smooth: true,
      symbol: 'circle',
      symbolSize: 5,
      itemStyle: {
        color: '#f56c6c'
      },
      areaStyle: {
        opacity: 0.3
      }
    },
    {
      name: '高危',
      type: chartType.value,
      data: mockTrendData.value.high,
      smooth: true,
      symbol: 'circle',
      symbolSize: 5,
      itemStyle: {
        color: '#e6a23c'
      },
      areaStyle: {
        opacity: 0.3
      }
    },
    {
      name: '中危',
      type: chartType.value,
      data: mockTrendData.value.medium,
      smooth: true,
      symbol: 'circle',
      symbolSize: 5,
      itemStyle: {
        color: '#409eff'
      },
      areaStyle: {
        opacity: 0.3
      }
    },
    {
      name: '低危',
      type: chartType.value,
      data: mockTrendData.value.low,
      smooth: true,
      symbol: 'circle',
      symbolSize: 5,
      itemStyle: {
        color: '#67c23a'
      },
      areaStyle: {
        opacity: 0.3
      }
    }
  ]
  
  // 根据显示模式调整系列配置
  if (severityChartMode.value === 'stack') {
    series.forEach(item => {
      item.stack = 'total'
    })
  } else if (severityChartMode.value === 'group' && chartType.value === 'bar') {
    // 分组显示时的配置已在echarts中默认处理
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e0e6ed',
      textStyle: {
        color: '#303133'
      },
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: function(params) {
        let result = params[0].name + '<br/>'
        let total = 0
        params.forEach(param => {
          result += param.marker + param.seriesName + ': ' + param.value + '<br/>'
          total += param.value
        })
        result += '总计: ' + total
        return result
      }
    },
    legend: {
      data: ['严重', '高危', '中危', '低危'],
      top: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: chartType.value === 'line' ? false : true,
      data: mockTrendData.value.dates,
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      axisLabel: {
        color: '#606266',
        rotate: timeInterval.value === 'day' ? 45 : 0
      }
    },
    yAxis: {
      type: 'value',
      name: '数量',
      nameTextStyle: {
        color: '#606266'
      },
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      axisLabel: {
        color: '#606266',
        formatter: '{value}'
      },
      splitLine: {
        lineStyle: {
          color: '#f0f2f5',
          type: 'dashed'
        }
      }
    },
    series: series,
    animation: true
  }
  
  chartInstances.severityTrend.setOption(option)
}

const initVulnerabilityTypeChart = () => {
  if (vulnerabilityTypeChart.value) {
    chartInstances.vulnerabilityType = echarts.init(vulnerabilityTypeChart.value)
    updateVulnerabilityTypeChart()
  }
}

const updateVulnerabilityTypeChart = () => {
  if (!chartInstances.vulnerabilityType) return
  
  const typeLabels = {
    'sql_injection': 'SQL注入',
    'xss': '跨站脚本(XSS)',
    'command_injection': '命令注入',
    'csrf': '跨站请求伪造(CSRF)',
    'information_disclosure': '信息泄露',
    'unauthorized_access': '未授权访问',
    'configuration_error': '配置错误',
    'buffer_overflow': '缓冲区溢出',
    'password_policy': '密码策略',
    'outdated_components': '过时组件'
  }
  
  const data = Object.entries(mockTrendData.value.vulnerabilityTypes)
    .map(([key, value]) => ({ name: typeLabels[key], value: value }))
    .sort((a, b) => b.value - a.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e0e6ed',
      textStyle: {
        color: '#303133'
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle',
      formatter: function(name) {
        const item = data.find(d => d.name === name)
        return name + ': ' + (item ? item.value : 0)
      }
    },
    series: [
      {
        name: '漏洞类型',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 6,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ],
    animation: true
  }
  
  chartInstances.vulnerabilityType.setOption(option)
}

const initAssetTypeChart = () => {
  if (assetTypeChart.value) {
    chartInstances.assetType = echarts.init(assetTypeChart.value)
    updateAssetTypeChart()
  }
}

const updateAssetTypeChart = () => {
  if (!chartInstances.assetType) return
  
  const assetLabels = {
    'web_apps': 'Web应用',
    'api_services': 'API服务',
    'servers': '服务器',
    'databases': '数据库',
    'network_devices': '网络设备'
  }
  
  const data = Object.entries(mockTrendData.value.assetTypes)
    .map(([key, value]) => ({ name: assetLabels[key], value: value }))
    .sort((a, b) => b.value - a.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e0e6ed',
      textStyle: {
        color: '#303133'
      }
    },
    series: [
      {
        name: '资产类型',
        type: 'pie',
        radius: '70%',
        center: ['50%', '50%'],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          formatter: '{b}\n{c} ({d}%)'
        },
        itemStyle: {
          borderRadius: 6,
          borderColor: '#fff',
          borderWidth: 2
        }
      }
    ],
    animation: true
  }
  
  chartInstances.assetType.setOption(option)
}

const initFixTimeTrendChart = () => {
  if (fixTimeTrendChart.value) {
    chartInstances.fixTimeTrend = echarts.init(fixTimeTrendChart.value)
    updateFixTimeTrendChart()
  }
}

const updateFixTimeTrendChart = () => {
  if (!chartInstances.fixTimeTrend) return
  
  let data = []
  let xAxisData = []
  let title = ''
  
  switch (fixTimeTrendType.value) {
    case 'by_severity':
      data = [
        { name: '严重', value: mockTrendData.value.fixTimes.by_severity.critical },
        { name: '高危', value: mockTrendData.value.fixTimes.by_severity.high },
        { name: '中危', value: mockTrendData.value.fixTimes.by_severity.medium },
        { name: '低危', value: mockTrendData.value.fixTimes.by_severity.low }
      ]
      xAxisData = ['严重', '高危', '中危', '低危']
      title = '按严重程度'
      break
    case 'by_type':
      data = Object.entries(mockTrendData.value.fixTimes.by_type)
        .map(([key, value]) => ({ name: key, value: value }))
      xAxisData = data.map(item => item.name)
      title = '按资产类型'
      break
    case 'by_asset':
      data = Object.entries(mockTrendData.value.fixTimes.by_vulnerability)
        .map(([key, value]) => ({ name: key, value: value }))
      xAxisData = data.map(item => keyToLabel(key))
      title = '按漏洞类型'
      break
  }
  
  function keyToLabel(key) {
    const labels = {
      'sql_injection': 'SQL注入',
      'xss': 'XSS',
      'command_injection': '命令注入',
      'csrf': 'CSRF',
      'information_disclosure': '信息泄露',
      'web_apps': 'Web应用',
      'api_services': 'API服务',
      'servers': '服务器',
      'databases': '数据库',
      'network_devices': '网络设备'
    }
    return labels[key] || key
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e0e6ed',
      textStyle: {
        color: '#303133'
      },
      formatter: function(params) {
        return params[0].name + '<br/>平均修复时间: ' + params[0].value + ' 天'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      axisLabel: {
        color: '#606266',
        rotate: xAxisData.length > 5 ? 45 : 0
      }
    },
    yAxis: {
      type: 'value',
      name: '天数',
      nameTextStyle: {
        color: '#606266'
      },
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      axisLabel: {
        color: '#606266',
        formatter: '{value} 天'
      },
      splitLine: {
        lineStyle: {
          color: '#f0f2f5',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '平均修复时间',
        type: 'bar',
        data: data.map(item => item.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ]),
          borderRadius: [4, 4, 0, 0]
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c} 天',
          color: '#606266'
        },
        markLine: {
          data: [
            { type: 'average', name: '平均值' }
          ],
          label: {
            formatter: '平均: {c} 天'
          }
        }
      }
    ],
    animation: true
  }
  
  chartInstances.fixTimeTrend.setOption(option)
}

const initPredictionChart = () => {
  if (predictionChart.value) {
    chartInstances.prediction = echarts.init(predictionChart.value)
    updatePredictionChart()
  }
}

const updatePredictionChart = () => {
  if (!chartInstances.prediction) return
  
  const allDates = [...mockTrendData.value.dates, ...mockTrendData.value.predictions.dates]
  const actualData = [...mockTrendData.value.totalVulnerabilities, ...Array(mockTrendData.value.predictions.dates.length).fill(null)]
  const predictedData = [...Array(mockTrendData.value.dates.length).fill(null), ...mockTrendData.value.predictions.totalVulnerabilities]
  
  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e0e6ed',
      textStyle: {
        color: '#303133'
      },
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['实际值', '预测值'],
      top: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: allDates,
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      axisLabel: {
        color: '#606266',
        rotate: 45
      },
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '漏洞数量',
      nameTextStyle: {
        color: '#606266'
      },
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      axisLabel: {
        color: '#606266',
        formatter: '{value}'
      },
      splitLine: {
        lineStyle: {
          color: '#f0f2f5',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '实际值',
        type: 'line',
        data: actualData,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: '#5470c6'
        },
        lineStyle: {
          width: 3
        }
      },
      {
        name: '预测值',
        type: 'line',
        data: predictedData,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: '#91cc75'
        },
        lineStyle: {
          width: 3,
          type: 'dashed'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(145, 204, 117, 0.5)' },
            { offset: 1, color: 'rgba(145, 204, 117, 0.1)' }
          ])
        }
      }
    ],
    markLine: {
      silent: true,
      data: [
        {
          xAxis: mockTrendData.value.dates[mockTrendData.value.dates.length - 1],
          lineStyle: {
            type: 'dashed',
            color: '#606266'
          },
          label: {
            formatter: '预测起始点',
            position: 'end'
          }
        }
      ]
    },
    animation: true
  }
  
  chartInstances.prediction.setOption(option)
}

const initAnomalyChart = () => {
  if (anomalyChart.value) {
    chartInstances.anomaly = echarts.init(anomalyChart.value)
    updateAnomalyChart()
  }
}

const updateAnomalyChart = () => {
  if (!chartInstances.anomaly) return
  
  // 创建异常点数据
  const anomalyPoints = mockTrendData.value.anomalies.map(anomaly => {
    const index = mockTrendData.value.dates.indexOf(anomaly.date)
    if (index !== -1) {
      return {
        value: [index, mockTrendData.value.newVulnerabilities[index]],
        itemStyle: {
          color: getSeverityColor(anomaly.severity)
        },
        name: anomaly.description,
        anomaly: anomaly
      }
    }
    return null
  }).filter(Boolean)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e0e6ed',
      textStyle: {
        color: '#303133'
      },
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: function(params) {
        let result = mockTrendData.value.dates[params[0].dataIndex] + '<br/>'
        params.forEach(param => {
          if (param.data && param.data.anomaly) {
            result += param.marker + '异常: ' + param.data.anomaly.description + '<br/>'
            result += '严重程度: ' + param.data.anomaly.severity + '<br/>'
            result += '置信度: ' + param.data.anomaly.confidence + '%'
          } else {
            result += param.marker + param.seriesName + ': ' + param.value + '<br/>'
          }
        })
        return result
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: mockTrendData.value.dates,
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      axisLabel: {
        color: '#606266',
        rotate: timeInterval.value === 'day' ? 45 : 0
      }
    },
    yAxis: {
      type: 'value',
      name: '新增漏洞数',
      nameTextStyle: {
        color: '#606266'
      },
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      axisLabel: {
        color: '#606266',
        formatter: '{value}'
      },
      splitLine: {
        lineStyle: {
          color: '#f0f2f5',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '新增漏洞数',
        type: 'line',
        data: mockTrendData.value.newVulnerabilities,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: '#5470c6'
        },
        lineStyle: {
          width: 2
        }
      },
      {
        name: '异常点',
        type: 'scatter',
        data: anomalyPoints,
        symbolSize: 15,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        },
        select: {
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 2
          }
        }
      }
    ],
    animation: true
  }
  
  chartInstances.anomaly.setOption(option)
  
  // 添加点击事件处理异常查看
  chartInstances.anomaly.off('click')
  chartInstances.anomaly.on('click', params => {
    if (params.data && params.data.anomaly) {
      viewAnomalyDetails(params.data.anomaly)
    }
  })
}

const updateCharts = () => {
  updateVulnerabilityTrendChart()
  updateSeverityTrendChart()
  updateVulnerabilityTypeChart()
  updateAssetTypeChart()
  updateFixTimeTrendChart()
  updatePredictionChart()
  updateAnomalyChart()
}

const handleDateRangeChange = () => {
  loadTrendData().then(() => {
    updateCharts()
  })
}

const handleSeverityChartCommand = (command) => {
  severityChartMode.value = command
  updateSeverityTrendChart()
}

const getRiskLevelClass = (score) => {
  if (score < 30) return 'risk-level-low'
  if (score < 60) return 'risk-level-medium'
  if (score < 80) return 'risk-level-high'
  return 'risk-level-critical'
}

const getRiskLevelText = (score) => {
  if (score < 30) return '低风险'
  if (score < 60) return '中风险'
  if (score < 80) return '高风险'
  return '严重风险'
}

const getSeverityColor = (severity) => {
  const colors = {
    'critical': '#f56c6c',
    'high': '#e6a23c',
    'medium': '#409eff',
    'low': '#67c23a'
  }
  return colors[severity] || '#909399'
}

const getSeverityTag = (severity) => {
  const types = {
    'critical': 'danger',
    'high': 'warning',
    'medium': 'primary',
    'low': 'success'
  }
  return types[severity] || 'info'
}

const getAnomalyTypeTag = (type) => {
  const types = {
    '漏洞数量激增': 'warning',
    '高危漏洞集中': 'danger',
    '修复率异常下降': 'primary',
    '未修复漏洞积累': 'warning'
  }
  return types[type] || 'info'
}

const viewAnomalyDetails = (anomaly) => {
  selectedAnomaly.value = anomaly
  showAnomalyDetailsDialog.value = true
}

const exportAnomalyDetails = () => {
  if (!selectedAnomaly.value) return
  
  ElMessage.success('异常详情导出成功')
}

const exportTrendsData = () => {
  loading.value = true
  loadingText.value = '导出数据中...'
  try {
    // 模拟导出操作
    setTimeout(() => {
      ElMessage.success('趋势数据导出成功')
      loading.value = false
    }, 1500)
  } catch (error) {
    console.error('导出趋势数据失败:', error)
    ElMessage.error('导出趋势数据失败，请重试')
    loading.value = false
  }
}

const refreshTrends = () => {
  loadTrendData().then(() => {
    updateCharts()
    ElNotification.success({
      title: '成功',
      message: '趋势数据已刷新'
    })
  })
}

const handleResize = () => {
  // 调整图表大小
  Object.values(chartInstances).forEach(chart => {
    if (chart && typeof chart.resize === 'function') {
      chart.resize()
    }
  })
}

// 生命周期钩子
onMounted(() => {
  // 设置默认日期范围
  dateRange.value = [defaultStartDate, defaultEndDate]
  
  // 加载数据
  loadTrendData().then(() => {
    // 初始化图表
    setTimeout(() => {
      initCharts()
    }, 100)
  })
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 销毁图表实例
  Object.values(chartInstances).forEach(chart => {
    if (chart && typeof chart.dispose === 'function') {
      chart.dispose()
    }
  })
  
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.vulnerability-trends-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.trends-card {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.analysis-config {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.advanced-filters {
  margin-top: 10px;
}

.metrics-overview {
  margin-bottom: 20px;
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.metric-content {
  padding: 10px 0;
}

.metric-details {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
}

.trend-indicator {
  font-size: 14px;
  font-weight: 500;
}

.trend-up {
  color: #f56c6c;
}

.trend-down {
  color: #67c23a;
}

.trend-neutral {
  color: #909399;
}

.risk-level {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  margin-top: 10px;
}

.risk-level-low {
  background-color: #f0f9ff;
  color: #36cfc9;
}

.risk-level-medium {
  background-color: #ecf5ff;
  color: #409eff;
}

.risk-level-high {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.risk-level-critical {
  background-color: #fef0f0;
  color: #f56c6c;
}

.trends-charts {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-controls {
  display: flex;
  gap: 10px;
}

.chart-container {
  height: 400px;
  width: 100%;
}

.anomalies-list {
  margin-top: 20px;
}

.anomalies-list h4 {
  margin-bottom: 10px;
  color: #303133;
}

.analysis-summary {
  margin-bottom: 20px;
}

.summary-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.summary-section h4 {
  margin-bottom: 10px;
  color: #303133;
  font-size: 16px;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.summary-section p,
.summary-section ul {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.summary-section ul {
  padding-left: 20px;
}

.summary-section li {
  margin-bottom: 5px;
}

.anomaly-details {
  padding: 10px 0;
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .summary-content {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }
}

@media (max-width: 768px) {
  .vulnerability-trends-container {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .analysis-config {
    padding: 15px;
  }
  
  .chart-container {
    height: 300px;
  }
  
  .summary-content {
    grid-template-columns: 1fr;
  }
  
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .chart-controls {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
}

@media (max-width: 480px) {
  .vulnerability-trends-container {
    padding: 5px;
  }
  
  .analysis-config {
    padding: 10px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .metric-details {
    flex-direction: column;
    gap: 5px;
  }
}

/* 深色模式适配 */
:global(.dark) .vulnerability-trends-container {
  background-color: #1a1a1a;
}

:global(.dark) .analysis-config {
  background-color: #2c2c2c;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

:global(.dark) .summary-section h4 {
  color: #e0e0e0;
  border-left-color: #66b1ff;
}

:global(.dark) .summary-section p,
:global(.dark) .summary-section ul {
  color: #a0a0a0;
}

:global(.dark) .anomalies-list h4 {
  color: #e0e0e0;
}

:global(.dark) .loading-mask {
  background-color: rgba(26, 26, 26, 0.8);
}
</style>